<template>
	<view class="customTokens">
		<HeaderBar title="添加代币" showBack fixed>
			<template #right>
				<view class="help">
					<image src="../../static/images/home/help.png" class="icon" mode=""></image>
				</view>
			</template>
		</HeaderBar>
		<view class="contentBox">
			<view class="from">
				<view class="lable flex">
					代币合约
					<view class="search" :data-tokenAddress="tokenAddress" :data-address="address" :data-ymbol="ymbol"
						:data-demail="demail" :data-addressInfo="addressInfo" :data-selectChain="chainInfo"
						:data-rpc="rpc" :data-erc20="erc20" @tap="renderjs.loadScripts">
						搜索
					</view>
				</view>
				<view class="inputBox">
					<input type="text" v-model="tokenAddress" class="input" placeholder-style="color:#B2B2B2"
						placeholder="请输入代币合约地址" />
				</view>
			</view>
			<view class="from">
				<view class="lable">
					代币符号
				</view>
				<view class="inputBox">
					<input type="text" v-model="ymbol" disabled class="input" placeholder-style="color:#B2B2B2"
						placeholder="请输入代币符号" />
				</view>
			</view>
			<view class="from">
				<view class="lable">
					代币精度
				</view>
				<view class="inputBox">
					<input type="text" v-model="demail" disabled class="input" placeholder-style="color:#B2B2B2"
						placeholder="请输入代币精度" />
				</view>
			</view>
		</view>
		<!-- <u-notify ref="error"></u-notify> -->
		<view class="btn_grounp">
			<view class="btn close" @tap="back">
				取消
			</view>
			<view class="btn confim" :class="{'disabled':tokenAddress&&ymbol&&demail}" @tap="setToken">
				确认
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				tokenAddress: "",
				ymbol: "",
				demail: "",
				erc20: null,
				tokenInfo: {}
			}
		},
		computed: {
			rpc() {
				return this.$store.getters.getRpc
			},
			chainInfo() {
				return this.$store.getters.chainInfo
			},
			addressInfo() {
				return this.$store.getters.addressInfo
			},
			address() {
				return this.$store.getters.getAddress;
			},
			chainId() {
				return this.$store.getters.getChainId;
			},
		},
		mounted() {
			this.erc20 = this.chainId == 0 ? this.$config.tronERC20 : this.$config.erc20
			uni.hideLoading();
		},
		methods: {
			showLoad() {
				uni.showLoading({
					title: '加载中',
					mask: true,
				});
			},
			heiLoad() {
				uni.hideLoading()
			},
			updataTokes(tokens) {
				this.ymbol = tokens.tokensymbol
				this.demail = tokens.tokendemail
				this.tokenInfo = tokens
			},
			setToken() {
				if (!this.tokenAddress || !this.ymbol || !this.demail) {
					return
				}
				let tip = ""
				if (this.tokenAddress == "") {
					tip = "请输入合约地址"
				} else if (this.ymbol == "") {
					tip = "请输入代币符号"
				} else if (this.demail == "") {
					tip = "请输入代币精度"
				} else if (this.ymbol != this.tokenInfo.tokensymbol) {
					tip = "代币符号有误"
				} else if (this.demail != this.tokenInfo.tokendemail) {
					tip = "代币精度有误"
				}
				if (tip != '') {
					return this.error(tip)
				}
				uni.$db.select('list', { // 普通查询
					from: 'choinList',
					where: [{
						address: `= "${this.address}"`,
						chainId: `= "${this.chainId}"`,
						tokenaddress: `= "${this.tokenAddress}"`,
					}]
				}).then(res => {
					if (res.length == 0) {
						uni.$db.insert('list', 'choinList', this.tokenInfo).then((res) => {
							this.$updateWalletInfo()
							uni.switchTab({
								url: '/pages/index/index', // 这里的路径是 tabBar 页面在项目中的路径
								success() {},
								fail(err) {}
							});
						}).catch((err) => {});
					} else {
						this.error("代币已存在")
						uni.switchTab({
							url: '/pages/index/index', // 这里的路径是 tabBar 页面在项目中的路径
							success() {
							},
							fail(err) {}
						});
					}
				})

			},
			showLoad() {
				uni.showLoading({
					title: '',
					mask: true,
				});
			},
			hideLoad() {
				uni.hideLoading();
			},
			error(tip) {
				uni.showToast({
					title: tip,
					position: "bottom",
					icon: "none",
					duration: 2000
				});
			},
			back() {
				uni.navigateBack();
			}
		}
	}
</script>
<script module="renderjs" lang="renderjs">
	export default {
		data() {
			return {
				ethjsLoadState: false,
				tronjsLoadState: false,
			}
		},
		mounted() {
			const ethersScript = document.createElement('script');
			ethersScript.src = 'static/script/ethers-5.2.umd.min.js';
			ethersScript.onload = (e) => {
				this.ethjsLoadState = true
			};
			document.head.appendChild(ethersScript);
			const tronWebScript = document.createElement('script');
			tronWebScript.src = 'static/script/newTronWeb.js';
			tronWebScript.onload = () => {
				this.tronjsLoadState = true
			};
			document.head.appendChild(tronWebScript);
		},
		methods: {
			loadScripts(e) {
				if (!this.ethjsLoadState) return false;
				if (!this.tronjsLoadState) return false;
				let tip = ""
				if (e.target.dataset.tokenAddress != "") {
					this.$ownerInstance.callMethod('showLoad');
					if (e.target.dataset.selectChain.chainType == "ETH") {
						this.getToken(e.target.dataset)
					} else {
						this.getTronToken(e.target.dataset)
					}
				} else {
					tip = "请输入合约地址"
				}
				if (tip != "") {
					this.$ownerInstance.callMethod('error', tip)
					return
				}

			},
			async getTronToken(config) {
				let {
					tokenAddress,
					address,
					selectChain,
					demail,
					ymbol,
					addressInfo,
					erc20,
					rpc
				} = config
				try {
					let tronWeb = new TronWeb.TronWeb({
						fullHost: rpc ? rpc : selectChain.defultRPC,
						privateKey: addressInfo.privateKey
					})
					let customToken = {
						address: address,
						chainType: selectChain.chainType,
						chainName: selectChain.chainName,
						chainId: selectChain.chainId,
						tokenaddress: tokenAddress,
						tokenname: "",
						tokenimg: "",
						tokennum: "",
						tokendemail: demail,
						tokensymbol: ymbol,
						tokenprice: "1",
					}
					tronWeb.setAddress(address);
					// 获取合约实例
					let tokenContract = await tronWeb.contract(erc20, tokenAddress);
					// // 调用合约方法
					let [tokenName, tokenSymbol, tokenDecimals] = await Promise.all([
						tokenContract.name().call(),
						tokenContract.symbol().call(),
						tokenContract.decimals().call()
					]);
					customToken.tokenname = tokenName; // 获取代币名称
					customToken.tokensymbol = tokenSymbol; // 获取代币符号
					customToken.tokendemail = tokenDecimals.toString(); // 获取代币小数位数
					this.$ownerInstance.callMethod('updataTokes', customToken);
					this.$ownerInstance.callMethod('hideLoad');
				} catch (e) {
					this.$ownerInstance.callMethod('hideLoad');
					this.$ownerInstance.callMethod('error', "合约地址有误")
				}
			},
			async getToken(config) {
				let {
					tokenAddress,
					address,
					selectChain,
					demail,
					ymbol,
					erc20,
					rpc
				} = config
				try {
					const provider = new ethers.providers.JsonRpcProvider(rpc ? rpc : selectChain.defultRPC);
					let customToken = {
						address: address,
						chainType: selectChain.chainType,
						chainName: selectChain.chainName,
						chainId: selectChain.chainId,
						tokenaddress: tokenAddress,
						tokenname: "",
						tokenimg: "",
						tokennum: "0",
						tokendemail: demail,
						tokensymbol: ymbol,
						tokenprice: "1",
					}
					let tokenContract = new ethers.Contract(tokenAddress, erc20, provider);
					let [tokenName, tokenSymbol, tokenDecimals] = await Promise.all([
						tokenContract.name(),
						tokenContract.symbol(),
						tokenContract.decimals()
					]);
					customToken.tokenname = tokenName; // 获取代币名称
					customToken.tokensymbol = tokenSymbol; // 获取代币符号
					customToken.tokendemail = tokenDecimals.toString(); // 获取代币小数位
					this.$ownerInstance.callMethod('updataTokes', customToken);
					this.$ownerInstance.callMethod('hideLoad');
				} catch (e) {
					this.$ownerInstance.callMethod('hideLoad');
					this.$ownerInstance.callMethod('error', "合约地址有误")
				}
			},
		}
	}
</script>

<style lang="scss" scoped>
	.customTokens {
		height: 100%;
		font-size: 36upx;
		color: #3D3D3D;
		display: flex;
		flex-direction: column;

		.help {
			display: flex;

			.icon {
				width: 42upx;
				height: 42upx;
			}
		}

		.contentBox {
			flex: 1;
			border-top: 1upx solid #D8D8D8;
			padding-left: 48upx;

			.from {
				padding-top: 32upx;
				border-bottom: 1upx solid #D8D8D8;
				padding-bottom: 10upx;

				.lable {
					display: flex;
					justify-content: space-between;
					padding-right: 48upx;
					align-items: center;

					.search {
						font-size: 26upx;
						color: #368321;
					}
				}

				.inputBox {
					padding: 10upx 10upx 10upx 0;

					.input {
						font-size: 30upx;
						padding-right: 20upx;
					}
				}
			}
		}

		.btn_grounp {
			padding: 0 30upx 144upx;
			display: flex;
			justify-content: space-between;

			.btn {
				width: 312upx;
				height: 88upx;
				text-align: center;
				line-height: 88upx;
				font-size: 36upx;
				border-radius: 10upx;
			}

			.close {
				color: #B2B2B2;
				background: #F5F6F8;
			}

			.confim {
				color: #F6F6F6;
				background: linear-gradient(180deg, #CEF3D3 100%, #297814 61%);
			}

			.disabled {
				background: linear-gradient(180deg, #A9E993 0%, #368321 100%);
			}
		}
	}
</style>